<?php
// Avoid direct calls to this file where wp core files not present
if (!function_exists ('add_action')) {
		header('Status: 403 Forbidden');
		header('HTTP/1.1 403 Forbidden');
		exit();
}

global $echotheme_options;
$echotheme_options  = get_option('echotheme_options');

/**
* Echotheme_Theme_Options
*/
class Echotheme_Theme_Options
{
	
	public function echotheme_Theme_Options()
	{
		// delete_option( "echotheme_options");
		add_action('admin_menu', array(&$this, 'echotheme_admin_menu'));
		add_action('admin_init', array(&$this, 'register_echotheme_theme_settings'));
		add_action('admin_post_save_echotheme_options', array(&$this, 'on_save_changes'));
	}
	
	public function init_echotheme_theme_options()
	{
		global $echotheme_options;
	    if( $echotheme_options['reset_to_defaults'] == 'yes' ) {
			delete_option( "echotheme_options");
		}
		
		if (! get_option("echotheme_options")) {
			add_option( "echotheme_options",
			    array(
					"reset_to_defaults" => '',
					'custom_logo_img' => get_bloginfo('template_url') . '/images/logo.png',
			    	"show_contact_fields" => "yes",
				    "contact_field_name1" => "Address:",
				    "contact_field_value1" => "123 Street Name, Suite #",
				    "contact_field_value2" => "City, State 12345, Country",
				    "contact_field_name3" => "Phone:",
				    "contact_field_value3" => "(123) 123-4567",
				    "contact_field_name4" => "Fax:",
				    "contact_field_value4" => "(123) 123-4567",
				    "contact_field_name5" => "Toll Free:",
				    "contact_field_value5" => "(800) 123-4567",
				    "contact_sidebar" => "left",
				    "NA_phone_format" => "", // North American phone number check, disabled by default
				    "email_receipients" => get_option('admin_email'),
				    "recaptcha_enabled" => "no",
				    "recaptcha_publickey" => "",
				    "recaptcha_privatekey" => "",
				    "recaptcha_theme" => "white",
				    "recaptcha_lang" => "en",
			    )
			);
		}
	}
	
	public function echotheme_admin_menu()
	{
		$this->init_echotheme_theme_options();
		//Add the echotheme options page to the Themes' menu
		$this->pagehook = add_theme_page('Echotheme Options', esc_html__('Theme Options', 'echotheme'), 'manage_options', 'echotheme_options_page', array(&$this, 'echotheme_generate_options_page'));
		add_action('load-'.$this->pagehook, array(&$this, 'on_load_page'));
	}
	
	public function register_echotheme_theme_settings()
	{
		register_setting( 'echotheme_options_page', 'echotheme_options', array(&$this, 'validate_options') );
	    // register_setting( 'echotheme_options_page', array(&$this, 'another_of_my_options') );
	}
	
	public function on_load_page()
	{
		wp_enqueue_style('style', get_template_directory_uri().'/inc/admin/style.css', false, '1.0', 'screen');
		wp_enqueue_style('thickbox');
		wp_enqueue_script('thickbox');
		wp_enqueue_script('media-upload');
		// wp_register_script('admin-scripts', get_template_directory_uri().'/inc/admin/scripts.js.php', array('jquery','media-upload','thickbox'), '1.0', false);
		wp_register_script('admin-scripts', get_template_directory_uri().'/inc/admin/scripts.js', array('jquery','media-upload','thickbox'), '1.0', false);
		wp_enqueue_script('admin-scripts');
		// load tablednd scripts
		wp_register_script('tablednd', get_template_directory_uri().'/inc/admin/jquery.tablednd.js', array('jquery'), '0.5', false);
		wp_enqueue_script('tablednd');
		// load uloadify scripts
		wp_enqueue_style('uploadify-style', get_template_directory_uri().'/inc/admin/uploadify/uploadify.css', false, '2.1.4', 'screen');
		wp_register_script('swfobject', get_template_directory_uri().'/inc/admin/uploadify/swfobject.js', array('jquery'), '2.2', false );
		wp_enqueue_script('swfobject');
		wp_register_script('jquery.uploadify', get_template_directory_uri().'/inc/admin/uploadify/jquery.uploadify.min.js', array('jquery'), '2.1.4', false );
		wp_enqueue_script('jquery.uploadify');
		//load color picker scripts
		wp_enqueue_style('qf-colorpicker-style', get_template_directory_uri().'/inc/admin/colorpicker/css/colorpicker.css', false, '1.0', 'screen');
		wp_register_script('qf-colorpicker', get_template_directory_uri().'/inc/admin/colorpicker/js/colorpicker.js', array('jquery'), '1.0.0', false );
		wp_enqueue_script('qf-colorpicker');

		// load javascripts to allow drag/drop, expand/collapse and hide/show of boxes
		wp_enqueue_script('common');
		wp_enqueue_script('wp-lists');
		wp_enqueue_script('postbox');
		
		// foreach ($this->sections as $section => $options) {
		// 	add_meta_box("echotheme-custom-$section-metabox", esc_html__(ucfirst($section) . ' Options', 'echotheme'), array(&$this, 'custom_options_contentbox'), $this->pagehook, 'normal', 'core', array('section' => $section));
		// }
		add_meta_box('echotheme-general-options-metabox', esc_html__('General Options', 'echotheme'), array(&$this, 'general_options_contentbox'), $this->pagehook, 'normal', 'core');
		add_meta_box('echotheme-contact_page-options-metabox', esc_html__('Contact Page', 'echotheme'), array(&$this, 'contact_page_options_contentbox'), $this->pagehook, 'normal', 'core');
		
		
	}
	
	public function validate_options($input)
	{
		global $echotheme_options;
		$input['reset_to_defaults'] = $input['reset_to_defaults'];
		
		
		//Contact Information Fields
		$input['contact_field_name1'] = stripslashes($input['contact_field_name1']);
		$input['contact_field_value1'] = stripslashes($input['contact_field_value1']);
		$input['contact_field_name2'] = stripslashes($input['contact_field_name2']);
		$input['contact_field_value2'] = stripslashes($input['contact_field_value2']);
		$input['contact_field_name3'] = stripslashes($input['contact_field_name3']);
		$input['contact_field_value3'] = stripslashes($input['contact_field_value3']);
		$input['contact_field_name4'] = stripslashes($input['contact_field_name4']);
		$input['contact_field_value4'] = stripslashes($input['contact_field_value4']);
		$input['contact_field_name5'] = stripslashes($input['contact_field_name5']);
		$input['contact_field_value5'] = stripslashes($input['contact_field_value5']);
		$input['contact_field_name6'] = stripslashes($input['contact_field_name6']);
		$input['contact_field_value6'] = stripslashes($input['contact_field_value6']);
		$input['contact_field_name7'] = stripslashes($input['contact_field_name7']);
		$input['contact_field_value7'] = stripslashes($input['contact_field_value7']);
		$input['contact_sidebar'] = ($input['contact_sidebar']) ? $input['contact_sidebar'] : $udesign_options['contact_sidebar'];
                $input['NA_phone_format'] = $input['NA_phone_format'];
		$email_receipients = $this->email_receipients_are_valid($input['email_receipients']); // validate email(s)
		$input['email_receipients'] = ( $email_receipients ) ?  $email_receipients: $udesign_options['email_receipients'];
		$input['recaptcha_publickey'] = trim(stripslashes($input['recaptcha_publickey']));
		$input['recaptcha_privatekey'] = trim(stripslashes($input['recaptcha_privatekey']));
		$input['recaptcha_enabled'] = ($input['recaptcha_publickey'] && $input['recaptcha_privatekey']) ? $input['recaptcha_enabled'] : 'no'; // disable ReCAPTCHA if publickey and privatekey are empty
		$input['recaptcha_theme'] = (  $input['recaptcha_theme'] ) ? $input['recaptcha_theme'] : $udesign_options['recaptcha_theme'];
		$input['recaptcha_lang'] = (  $input['recaptcha_lang'] ) ? $input['recaptcha_lang'] : $udesign_options['recaptcha_lang'];

		
		
		return $input;
	}
	
	public function on_save_changes()
	{
		// user permission check
		if ( !current_user_can('manage_options') )
			wp_die( esc_html__("Cheatin' uh?") );
		// cross check the given referer
		check_admin_referer( 'echotheme_options_page-options' );
		//lets redirect the post request into get request (you may add additional params at the url, if you need to show save results
		wp_redirect($_POST['_wp_http_referer']);
	}
	
	/**
	 * Validate email receipient(s) email addresses
	 *
	 * @param string $receipients, a string of CSV email addresses
	 * @return bool|mixed False on failure or a string of properly formatted CSV email addresses otherwise
	 */
	function email_receipients_are_valid ( $receipients ) {
	    	$emails_array = explode( ",", $receipients );
		foreach ( $emails_array as $email ) {
		    if ( !is_email( trim($email) ) )
			return false;
		}
		return implode( ', ', array_map( 'trim', $emails_array) ); // trim white spaced from beginning and end of email addresses
	}
	
	public function echotheme_generate_options_page()
	{
		// global screen column value to be able to have a sidebar in WordPress 2.8+
		global $screen_layout_columns;

		/* Messages to display saved and reset */
		if ( $_REQUEST['updated'] ) echo '<div id="message" class="updated fade"><p><strong>'.esc_html__('Settings saved.', 'echotheme').'</strong></p></div>';
		//if ( $_REQUEST['reset'] ) echo '<div id="message" class="updated fade"><p><strong>'.esc_html__('Settings reset.', 'echotheme').'</strong></p></div>'; ?>
		<div id="echotheme-metaboxes-general" class="wrap">
		    <div style="float:left; padding:10px 10px 0 0;"><img src="<?php echo get_template_directory_uri(); ?>/images/logo.png" width="150" height="44" /></div>
		    <h2 style="padding-top:25px;"><?php printf( __('Theme Options <small>(version %1$s)</small>', 'echotheme'), '0.1' ); ?></h2>

		    <form method="post" action="options.php">
<?php			settings_fields( 'echotheme_options_page' ); // Checks that the user can update options and also redirect the user back to the correct admin page (this form).
			$options = get_option('echotheme_options');
			// Allows the 'closed' state of metaboxes to be remembered
			wp_nonce_field('closedpostboxes', 'closedpostboxesnonce', false );
			// Allows the order of metaboxes to be remembered
			wp_nonce_field('meta-box-order', 'meta-box-order-nonce', false ); ?>

			<div id="poststuff" class="metabox-holder<?php echo 2 == $screen_layout_columns ? ' has-right-sidebar' : ''; ?>">
				<div id="post-body" class="has-sidebar">
					<div id="post-body-content" class="has-sidebar-content">
<?php					    do_meta_boxes($this->pagehook, 'normal', $options); ?>
<?php					    do_meta_boxes($this->pagehook, 'additional', $options); ?>
					    <fieldset style="margin:2px 0 0;"><legend class="screen-reader-text"><span><?php esc_attr_e('Reset to defaults', 'echotheme') ?></span></legend>
						<label for="reset_to_defaults">
						    <input name="echotheme_options[reset_to_defaults]" type="checkbox" id="reset_to_defaults" value="yes" />
						    <?php esc_attr_e('Reset to defaults', 'echotheme') ?>
						</label>
					    </fieldset>
					    <p class="submit">
						<input type="hidden" id="echotheme_submit" value="1" name="echotheme_submit"/>
						<input class="button-primary" type="submit" name="submit" value="<?php esc_attr_e('Save Changes', 'echotheme') ?>" />
					    </p>
					</div>
				</div>
				<br class="clear"/>
			</div>
		    </form>
<?php		    /* The reset button */; ?>
<!--		    <form method="post">
			<p class="submit">
			    <input name="reset" type="submit" value="Reset" />
			    <input type="hidden" name="action" value="reset" />
			</p>
		    </form> -->
		</div>
		<script type="text/javascript">
		    //<![CDATA[
		    jQuery(document).ready( function($) {
			    // close postboxes that should be closed
			    $('.if-js-closed').removeClass('if-js-closed').addClass('closed');
			    // postboxes setup
			    postboxes.add_postbox_toggles('<?php echo $this->pagehook; ?>');
		    });
		    //]]>
		</script>
<?php
	}
	
	function contact_page_options_contentbox( $options ) {
		$show_contact_fields = $options['show_contact_fields'];
		$contact_field_name1 = $options['contact_field_name1'];
		$contact_field_value1 = $options['contact_field_value1'];
		$contact_field_name2 = $options['contact_field_name2'];
		$contact_field_value2 = $options['contact_field_value2'];
		$contact_field_name3 = $options['contact_field_name3'];
		$contact_field_value3 = $options['contact_field_value3'];
		$contact_field_name4 = $options['contact_field_name4'];
		$contact_field_value4 = $options['contact_field_value4'];
		$contact_field_name5 = $options['contact_field_name5'];
		$contact_field_value5 = $options['contact_field_value5'];
		$contact_field_name6 = $options['contact_field_name6'];
		$contact_field_value6 = $options['contact_field_value6'];
		$contact_field_name7 = $options['contact_field_name7'];
		$contact_field_value7 = $options['contact_field_value7'];
		$contact_sidebar = $options['contact_sidebar'];
		$NA_phone_format = $options['NA_phone_format'];
		$email_receipients = $options['email_receipients'];
		
		include('metabox/contact.php');
		
		display_save_changes_button(); 
	}
	
	function general_options_contentbox($options)
	{
		include('metabox/general.php');
		display_save_changes_button();
	}
}

$myEchotheme_Options = new echotheme_Theme_Options();

function display_save_changes_button($section = null) {
		if ($section != null) {
			$section = '_' . $section;
		}
	    echo ('
		    <table class="form-table">
			<tbody>
			    <tr valign="top">
				<th scope="row">&nbsp;</th>
				<td>
				    <div class="submit" style="padding:10px 0 0 80px; float:right; clear:both;">
					<input type="hidden" id="echotheme' . $section . '_submit" value="1" name="echotheme_submit"/>
					<input class="button-primary" type="submit" name="submit" value="'.esc_attr__('Save Changes', 'echotheme').'" />
				    </div>
				</td>
			    </tr>
			</tbody>
		    </table>');
}

?>